//
//  BianjishangpinViewController.swift
//  联付商圈
//
//  Created by zhangqi on 2017/8/18.
//  Copyright © 2017年 lianfu. All rights reserved.
//

import UIKit
import Alamofire
import Kingfisher

class BianjishangpinViewController: BaseViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
    var leiid = ""
    var leiname = ""
    var spid = ""
    var flid = [Int]()
    var fenleiArr = [[String:Any]]()
    var shangpinArr = [[String:Any]]()
    var isTarget = true
    var targetRect = CGRect()
    
    
    @IBOutlet weak var querenLab: UILabel!
    
    @IBOutlet weak var backgroundImg: UIImageView!
    
    @IBOutlet weak var addShangpinView: UIView!
    
    @IBOutlet weak var addImg: UIImageView!
    
    @IBOutlet weak var addNameTex: UITextField!
    
    @IBOutlet weak var addYuanjiaTex: UITextField!
    
    @IBOutlet weak var addDangqianshoujiaTex: UITextField!
    
    @IBOutlet weak var addJieshaoTex: UITextField!
    
    @IBAction func addQuxiaoBtn(_ sender: UIButton) {
        addShangpinView.isHidden = true
        backgroundImg.isHidden = true
        addDangqianshoujiaTex.text = ""
        addYuanjiaTex.text = ""
        addNameTex.text = ""
        addJieshaoTex.text = ""
        addImg.image = UIImage(named:"4-1")
    }
    
    @IBAction func addQuerenBtn(_ sender: UIButton) {
        let dqjia = addDangqianshoujiaTex.text!
        let yjia = addYuanjiaTex.text!
        let proname = addNameTex.text!
        let proinfo = addJieshaoTex.text!
        let yuanjiaInt = Double(yjia)
        let dqjiaInt = Double(dqjia)
        if leiid == "" {
            self.noticeInfo("请选择分类", autoClear: true, autoClearTime: 2)
        } else if dqjia == "" || yjia == "" || proname == "" || proinfo == "" {
            self.noticeInfo("请补全信息", autoClear: true, autoClearTime: 2)
        } else {
            if (dqjiaInt ?? Double()) != 0.0 && (yuanjiaInt ?? Double()) != 0.0 {
                let x = UserDefaults.standard.object(forKey: "userInfo") as! NSDictionary
                let y = x["name"]!
                tianjiashangpin(lei: leiid, nowprice: dqjia, beprice: yjia, product_name: proname, product_info: proinfo, name: "\(y)", num: "\(0)")
                
            } else if (dqjiaInt ?? Double()) == 0.0 && (yuanjiaInt ?? Double()) == 0.0 {
                self.noticeInfo("价格填写错误", autoClear: true, autoClearTime: 2)
            }
        }
    }
    
    
    
    
    
    
    
    @IBAction func backBtn(_ sender: UIBarButtonItem) {
        if self.flid.count != 0 {
//            print(self.flid)
//            print(self.flid)
        shanchukongfeilei(lei:"\(self.flid)")
        } else if self.flid.count == 0 {
            self.navigationController?.popViewController(animated: true)
        }
    }
    
    @IBAction func fenleiadd(_ sender: UIBarButtonItem) {
        tanchuang()
    }
    
    @IBAction func shangpinadd(_ sender: UIButton) {
        if leiid == "" {
            self.noticeInfo("请选择分类", autoClear: true, autoClearTime: 2)
        } else if leiid != "" {
        addShangpinView.isHidden = false
        backgroundImg.isHidden = false
        querenLab.text = "将商品添加至" + leiname
        }
    }
    
    @IBOutlet weak var fenleiTableView: UITableView!
    
    @IBOutlet weak var shangpinTableView: UITableView!
    
    
    func shanchukongfeilei(lei:String){
        let parameters = ["lei_id":lei]
        let urlString = "https://www.beidikeji.com/life/public/jiekou/delfenlei?"
        let manager = Alamofire.SessionManager.default
        manager.session.configuration.timeoutIntervalForRequest = 45
        manager.request(urlString,method:.post,parameters: parameters).responseJSON {Request in
            switch Request.result {
            case .success:
                self.navigationController?.popViewController(animated: true)
            case .failure:
                self.noticeInfo("未知错误", autoClear: true, autoClearTime: 1)
            }
        }
    }

    
    
    func tanchuang(){
        let alertVC = UIAlertController(title: "添加分类", message: nil, preferredStyle: UIAlertControllerStyle.alert)
        let acSure = UIAlertAction(title: "确定", style: UIAlertActionStyle.destructive) { (UIAlertAction) -> Void in
            let x = alertVC.textFields!.first! as UITextField
            let y = x.text
            if y != "" {
               self.tianjiafenlei(lei: y!)
            } else if y == "" {
                self.noticeInfo("分类不能为空", autoClear: true, autoClearTime: 1)
            }
        }
        let acCancel = UIAlertAction(title: "取消", style: UIAlertActionStyle.cancel) { (UIAlertAction) -> Void in
            return
        }
        alertVC.addAction(acSure)
        alertVC.addAction(acCancel)
        alertVC.addTextField {
            (textField: UITextField!) -> Void in
            textField.placeholder = ""
        }
        self.present(alertVC, animated: true, completion: nil)
    }
    
    func shanchufenleitanchuang(){
        let alertVC = UIAlertController(title: "确定删除该分类？", message: "该分类下所属商品将一并删除", preferredStyle: UIAlertControllerStyle.alert)
        let acSure = UIAlertAction(title: "确定", style: UIAlertActionStyle.destructive) { (UIAlertAction) -> Void in
            
            self.shanchufenlei(fenleinm:self.leiname)
            self.jiazaifenlei()
        }
        let acCancel = UIAlertAction(title: "取消", style: UIAlertActionStyle.cancel) { (UIAlertAction) -> Void in
            return
        }
        alertVC.addAction(acSure)
        alertVC.addAction(acCancel)
        self.present(alertVC, animated: true, completion: nil)
    }

    
    func tianjiafenlei(lei:String){
        let x = UserDefaults.standard.object(forKey: "userInfo") as! NSDictionary
        let y = x["name"]!
        let parameters = ["name":"\(y)","lei_name":"\(lei)"]
        let urlString = "https://www.beidikeji.com/life/public/jiekou/fenleiadd?"
        let manager = Alamofire.SessionManager.default
        manager.session.configuration.timeoutIntervalForRequest = 45
        manager.request(urlString,method:.post,parameters: parameters).responseJSON {Request in
            switch Request.result {
            case .success:
                self.jiazaifenlei()
            case .failure:
                self.noticeInfo("未知错误", autoClear: true, autoClearTime: 1)
            }
        }
    }

    func jiazaifenlei(){
        let x = UserDefaults.standard.object(forKey: "userInfo") as! NSDictionary
        let y = x["name"]!
        let parameters = ["name":"\(y)"]
        let urlString = "https://www.beidikeji.com/life/public/jiekou/fenleisy?"
        let manager = Alamofire.SessionManager.default
        manager.session.configuration.timeoutIntervalForRequest = 45
        manager.request(urlString,method:.post,parameters: parameters).responseJSON {Request in
            switch Request.result {
            case .success:
                let json = JSON(data: Request.data!).arrayObject
                //print(json!)
                self.fenleiArr = json as! [[String:Any]]
                let x = self.fenleiArr.count
//                print(self.fenleiArr)
//                print(self.fenleiArr)
                if x == 0 {
                    self.noticeInfo("未添加商品", autoClear: true, autoClearTime: 2)
                    return
                } else if x != 0 {
                    self.flid = []
                    for  x in 0 ..< self.fenleiArr.count {
                        let y = self.fenleiArr[x]["id"] as! Int
                        self.flid.append(y)
                    }
                    
                    self.leiid = "\(self.fenleiArr[0]["id"]!)"
                    self.leiname = self.fenleiArr[0]["lei_name"] as! String
                    self.jiazaishangpin(lei:"\(self.fenleiArr[0]["id"]!)")
                    self.fenleiTableView.reloadData()
                    self.shangpinTableView.reloadData()
                }
                
            case .failure:
                self.noticeInfo("未知错误", autoClear: true, autoClearTime: 1)
            }
        }
    }

    func jiazaishangpin(lei:String){
        let parameters = ["lei_id":lei]
        let urlString = "https://www.beidikeji.com/life/public/jiekou/fenleisp?"
        let manager = Alamofire.SessionManager.default
        manager.session.configuration.timeoutIntervalForRequest = 45
        manager.request(urlString,method:.post,parameters: parameters).responseJSON {Request in
            switch Request.result {
            case .success:
                let json = JSON(data: Request.data!).arrayObject
                self.shangpinArr = json as! [[String:Any]]
                self.shangpinTableView.reloadData()
            case .failure:
                self.noticeInfo("未知错误", autoClear: true, autoClearTime: 1)
            }
        }
    }

    func tianjiashangpin(lei:String,nowprice:String,beprice:String,product_name:String,product_info:String,name:String,num:String){
        let parameters = ["lei_id":lei,"nowprice":nowprice,"beprice":beprice,"product_name":product_name,"product_info":product_info,"name":name,"num":num]
        let urlString = "https://www.beidikeji.com/life/public/jiekou/goodsadd?"
        let manager = Alamofire.SessionManager.default
        manager.session.configuration.timeoutIntervalForRequest = 45
        manager.request(urlString,method:.post,parameters: parameters).responseJSON {Request in
            switch Request.result {
            case .success:
                let json = JSON(data: Request.data!).dictionaryObject
                //print(json!)
                let a = json!["success"] as! [String:Any]
                let x = a["id"]!
                self.upimg(id:"\(x)")
            case .failure:
                self.noticeInfo("未知错误", autoClear: true, autoClearTime: 1)
            }
        }
    }
    

    func shanchushangpin(shangpinid:String,lei:String){
        let parameters = ["id":shangpinid,"lei_id":lei]
        let urlString = "https://www.beidikeji.com/life/public/jiekou/goodsdel?"
        let manager = Alamofire.SessionManager.default
        manager.session.configuration.timeoutIntervalForRequest = 45
        manager.request(urlString,method:.post,parameters: parameters).responseJSON {Request in
            switch Request.result {
            case .success:
                self.noticeInfo("编辑成功", autoClear: true, autoClearTime: 1)
                self.shangpinTableView.reloadData()
            case .failure:
                self.noticeInfo("未知错误", autoClear: true, autoClearTime: 1)
            }
        }
    }
    
    func shanchufenlei(fenleinm:String){
        let x = UserDefaults.standard.object(forKey: "userInfo") as! NSDictionary
        let y = x["name"]!
        let parameters = ["name":"\(y)","lei_name":fenleinm]
        let urlString = "https://www.beidikeji.com/life/public/jiekou/fenleidel?"
        let manager = Alamofire.SessionManager.default
        manager.session.configuration.timeoutIntervalForRequest = 45
        manager.request(urlString,method:.post,parameters: parameters).responseJSON {Request in
            switch Request.result {
            case .success:
                self.noticeInfo("编辑成功", autoClear: true, autoClearTime: 1)
                self.shangpinTableView.reloadData()
            case .failure:
                self.noticeInfo("未知错误", autoClear: true, autoClearTime: 1)
            }
        }
    }

    
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        addNameTex.delegate = self
        addYuanjiaTex.delegate = self
        addDangqianshoujiaTex.delegate = self
        addJieshaoTex.delegate = self
        shangpinTableView.tableFooterView = UIView(frame: CGRect.zero)
        fenleiTableView.tableFooterView = UIView(frame: CGRect.zero)
        addShangpinView.isHidden = true
        backgroundImg.isHidden = true
        fenleiTableView.tag = 101
        shangpinTableView.tag = 102      //cell1.addBtn.layer.cornerRadius = 12.0
        
        let tap = UITapGestureRecognizer(target : self,action : #selector(aler))
        tap.numberOfTapsRequired = 1
        addImg.isUserInteractionEnabled = true
        addImg.addGestureRecognizer(tap)
        addShangpinView.layer.cornerRadius = 12.0
        jiazaifenlei()
    }
    
    
    func aler(){
        let alertVC = UIAlertController(title: "添加相片", message: nil, preferredStyle: UIAlertControllerStyle.actionSheet)
        let acXiangji = UIAlertAction(title: "相机拍摄", style: UIAlertActionStyle.default) { (UIAlertAction) -> Void in
            self.camera()
        }
        let acXiangce = UIAlertAction(title: "相册选取", style: UIAlertActionStyle.default) { (UIAlertAction) -> Void in
            self.photo()
        }
        let acCancel = UIAlertAction(title: "取消", style: UIAlertActionStyle.cancel) { (UIAlertAction) -> Void in
            return
        }
        alertVC.addAction(acXiangji)
        alertVC.addAction(acXiangce)
        alertVC.addAction(acCancel)
        self.present(alertVC, animated: true, completion: nil)
    }
    
    func camera(){
        let pick:UIImagePickerController = UIImagePickerController()
        pick.delegate = self
        pick.sourceType = UIImagePickerControllerSourceType.camera
        self.present(pick, animated: true, completion: nil)
    }
    
    func photo(){
        let pick:UIImagePickerController = UIImagePickerController()
        pick.delegate = self
        pick.sourceType = UIImagePickerControllerSourceType.photoLibrary
        self.present(pick, animated: true, completion: nil)
    }


    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }
    
    override func viewWillAppear(_ animated: Bool) {
        self.navigationController?.navigationBar.isHidden = false
    }

    func upimg(id:String){
        let datata = UIImageJPEGRepresentation(self.addImg.image!, 0.3)
        let imageName = String(describing: NSDate()) + ".png"
        Alamofire.upload(multipartFormData: { multipartFormData in
            multipartFormData.append(datata!, withName: "photo", fileName: imageName, mimeType: "image/png")
            multipartFormData.append(id.data(using: String.Encoding.utf8)!, withName: "id")
        }, to: "https://www.beidikeji.com/life/public/jiekou/goodspicture?", encodingCompletion: { encodingResult in
            switch encodingResult {
            case .success(let upload, _, _):
                upload.responseJSON { Request in
                    switch Request.result {
                    case .success: break
                    case .failure: break
                    }
                }

                self.addShangpinView.isHidden = true
                self.backgroundImg.isHidden = true
                self.jiazaishangpin(lei:self.leiid)
                self.shangpinTableView.reloadData()
                self.addDangqianshoujiaTex.text = ""
                self.addYuanjiaTex.text = ""
                self.addNameTex.text = ""
                self.addJieshaoTex.text = ""
                self.addImg.image = UIImage(named:"4-1")
                self.noticeInfo("编辑成功", autoClear: true, autoClearTime: 1)
            case .failure( _):
                self.noticeInfo("未知错误", autoClear: true, autoClearTime: 1)
            }
            
        })

    }
    
    //MARK:- UIImagePickerControllerDelegate
    func imagePickerController(_ picker:UIImagePickerController, didFinishPickingMediaWithInfo
        info: [String :Any]){
        
        let type:String = (info[UIImagePickerControllerMediaType]as!String)
        
        if type=="public.image"
        {
            let img = info[UIImagePickerControllerOriginalImage] as? UIImage
            self.addImg.image = img
            picker.dismiss(animated:true, completion:nil)
        }
        
    }
    func imagePickerControllerDidCancel(_ picker:UIImagePickerController){
        picker.dismiss(animated:true, completion:nil)
    }
    
    
    


}

extension BianjishangpinViewController: UITableViewDelegate,UITableViewDataSource, UITextFieldDelegate, UITextViewDelegate {
    
    
    func setup(cell: ShangpinBianjiTableViewCell, atIndexPath indexPath: IndexPath) {
        let result = shangpinArr[indexPath.row] as NSDictionary
        let  or = result["image_url"] as? String
        let url = URL(string:or!)
        
        if cell.spImg.kf.webURL != url {
            let cellFrame = self.shangpinTableView.rectForRow(at: indexPath)
            var shouldLoadImage = true
            if self.isTarget && !self.targetRect.intersects(cellFrame) {
                let image = KingfisherManager.shared.cache.retrieveImageInDiskCache(forKey: or!, options: nil)
                if image == nil {
                    shouldLoadImage = false
                }
            }
            if shouldLoadImage {
                cell.spImg.kf.setImage(with: url, placeholder: nil, options: nil, progressBlock: nil, completionHandler: { (image, error, type, urls) in
                    if error == nil && url == urls {
                    }})}}}

    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if tableView.tag == 101 {
            return fenleiArr.count
        } else {
            return shangpinArr.count
        }
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        
        
        if tableView.tag == 101 {
            let cell = tableView.dequeueReusableCell(withIdentifier: "FenleiBianjiTableViewCell", for: indexPath) as! FenleiBianjiTableViewCell
            fenleiTableView.selectRow(at: IndexPath.init(row:0, section:0), animated: true, scrollPosition: .middle)
            cell.selectionStyle = UITableViewCellSelectionStyle.none
            cell.fenleiLab.text = (fenleiArr[indexPath.row]["lei_name"] as! String)
            return cell
        } else {
            let cell = tableView.dequeueReusableCell(withIdentifier: "ShangpinBianjiTableViewCell", for: indexPath) as! ShangpinBianjiTableViewCell
            cell.spName.text = (shangpinArr[indexPath.row]["product_name"] as! String)
            cell.spJiage.text = "¥" + "\(shangpinArr[indexPath.row]["nowprice"]!)"
            self.setup(cell: cell, atIndexPath: indexPath)
            return cell
        }
    }
    
    
    func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
        fenleiTableView.deleteRows(at: [indexPath as IndexPath], with: .fade)
        shangpinTableView.deleteRows(at: [indexPath as IndexPath], with: .fade)
    }
    
    
    
    func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? {
        if tableView.tag == 101 {
        let deleteAction = UITableViewRowAction(style: UITableViewRowActionStyle.default, title: "删除",handler: { (action, indexPath) -> Void in
            let x = self.fenleiArr.count
            if x == 0 {
                self.fenleiTableView.reloadData()
                self.shangpinTableView.reloadData()
                return
            } else if x != 0 {
                self.leiid = "\(self.fenleiArr[indexPath.row]["id"]!)"
                self.leiname = self.fenleiArr[indexPath.row]["lei_name"] as! String
                    self.shanchufenleitanchuang()
            }
            
        })
        return [deleteAction]
        } else {
            let deleteAction = UITableViewRowAction(style: UITableViewRowActionStyle.default, title: "删除",handler: { (action, indexPath) -> Void in
                let a = self.shangpinArr[indexPath.row]["id"]
                self.shanchushangpin(shangpinid:"\(a!)", lei: self.leiid)
                self.jiazaishangpin(lei: self.leiid)
            })
            return [deleteAction]
        }
    }
    
    func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
        return true
    }

    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        if tableView.tag == 101 {
            leiid = "\(fenleiArr[indexPath.row]["id"]!)"
            leiname = fenleiArr[indexPath.row]["lei_name"] as! String
            jiazaishangpin(lei:leiid)
        }
        
    }
    
    
    func scrollViewWillEndDragging(_ scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) {
        self.targetRect = CGRect(x: targetContentOffset.pointee.x, y: targetContentOffset.pointee.y, width: scrollView.frame.size.width, height: scrollView.frame.size.height)
        self.isTarget = true
    }
    
    func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
        self.isTarget = false
        self.loadImageForVisibleCells()
    }
    
    func loadImageForVisibleCells() {
        let visibleCells = self.shangpinTableView.visibleCells
        for cell in visibleCells {
            self.setup(cell: cell as! ShangpinBianjiTableViewCell, atIndexPath: self.shangpinTableView.indexPath(for: cell)!)
        }
    }
    

    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        textField.resignFirstResponder()
        UIView.animate(withDuration: 0.3) {
            self.view.transform = CGAffineTransform(translationX: 0, y: 0)
            self.view.frame = CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height)
        }
        return true
    }
    

    func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
        if (text == "\n") {
            textView.resignFirstResponder()
            return false
        }
        return true
    }


}

